<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace Publish\Controller;

use Common\Controller\HomebaseController;
include '../Common/function.php';
class SearchController extends HomebaseController {
	protected $terms_model;
	protected $person_model;
	protected $pub_img;
	protected $pub_story;
	protected $pub_video;
	protected $pub_history;
	protected $pub_information;
	protected $sys_terms;
	protected $sys_terms_relationships;

	function _initialize() {
		parent::_initialize();
		$this->terms_model = D("Publish/SystemTerms");
		$this->person_model = D("Publish/PubPerson");
		$this->pub_img = D("Publish/PubImage");
		$this->pub_story = D("Publish/PubStory");
		$this->pub_video = D("Publish/PubVideo");
		$this->pub_history = D("Publish/PubHistory");
		$this->pub_information = D("Publish/PubInformation");
		$this->sys_terms = D("Publish/SystemTerms");
		$this->sys_terms_relationships = D("Publish/SystemTermRelationships");
	}

	//搜索结果页面
	public function index() {
		$keyword = I('request.keyword/s', '');

		if (empty($keyword)) {
			$this->error("关键词不能为空！请重新输入！");
		}

		$this->assign("keyword", $keyword);
		$this->display(":search");
	}
	/*高级搜索页显示*/
	public function search() {
		$this->_getTermTree();
		$aa=isMobile();
		if($aa){
			
			$this->display("search_m");
		}else{
			$this->display();
		}
	}
	/*高级搜索条件查询结果--人物检索*/
	public function post_search(){
		$term_id = I("term_id"); // 总分类id
		$conditionArr = I("conditionArr"); //人物检索条件
		//循环多条件 ||为多条查询条件
		if(empty($conditionArr)){
			$this->error("输入条件不合法!");
		}else{
			foreach($conditionArr as $key => $value){
				switch ($value[0]){
					case 'name':
						if($value[2] == 'and') $where['a.name'] = array('like',"%$value[1]%");
						else $map['a.name'] = array('like',"%$value[1]%");
						break;
					case 'sex':
						$sex = (strpos('男',$value[1]) === 0)? 0: 1;
						if($value[2] == 'and') $where[$value[0]] = $sex;
						else $map[$value[0]] = $sex;
						break;
					case 'birthday':
						if($value[2] == 'and') $where['a.birthday'] = array('like',"%$value[1]%");
						else $map['a.birthday'] = array('like',"%$value[1]%");
						break;
					case 'die':
						if($value[2] == 'and') $where['a.die'] = array('like',"%$value[1]%");
						else $map['a.die'] = array('like',"%$value[1]%");
						break;
					case 'duty':
						if($value[2] == 'and') $where['a.duty'] = array('like',"%$value[1]%");
						else $map['a.duty'] = array('like',"%$value[1]%");
						break;
					case 'place':
						if($value[2] == 'and') $where['a.place'] = array('like',"%$value[1]%");
						else $map['a.place'] = array('like',"%$value[1]%");
						break;
					case 'abstract':
						if($value[2] == 'and') $where['a.abstract'] = array('like',"%$value[1]%");
						else $map['a.abstract'] = array('like',"%$value[1]%");
						break;
				}
			}
		}

		if(!empty($where)&& !empty($map)){
			$map['_logic'] = "OR";
			$condition['_complex'] = array(
				$where,
				$map,
				'_logic' => 'and'
			);
		}else if($where){
			$condition['_complex'] = $where;
		}else{
			$map['_logic'] = "OR";
			$condition['_complex'] = $map;
		}
		if($term_id == 0){ //没有总分类
			$screening_results = $this->person_model
				->alias('a')
				->where($condition)
				->order("a.listorder desc,a.id asc")
				->select();
		}else{ //有总分类id
			/*判断是否为一级类*/
			$grade = $this->sys_terms->find($term_id); //该分类下的信息
			$grade_num = count(explode('-',$grade['path']))-1; //获取分类等级数
			if($grade_num == 1){
				//是一级类情况，查询该一级类下的子分类信息
				$subclassification_info = $this->sys_terms->where("parent = $term_id")->select();
				//循环子分类id查询
				foreach($subclassification_info as $key => $value){
					//将多个数组放入$multi_screening_results中
					$multi_screening_results[$key] = $this->person_model
						->alias('a')
						->join('LEFT JOIN __SYSTEM_TERM_RELATIONSHIPS__ as b ON b.object_id = a.id')
						->join('RIGHT JOIN __SYSTEM_TERMS__ as c ON c.term_id = b.term_id')
						->field('a.*,b.object_id,c.term_id')
						->where($condition)
						->where("c.term_id =".$value['term_id'])
						->order("a.listorder desc,a.id asc")
						->select();
				}
				/*将多个子分类下的数组合并 放入$screening_results*/
				$i=0;
				foreach($multi_screening_results as $key => $value){
					foreach($value as $k =>$v){
						$screening_results[$i++] = $v;
					}
				}
			} else { //是二级类情况,直接使用二级分类id查询
				$screening_results = $this->person_model
					->alias('a')
					->join('LEFT JOIN __SYSTEM_TERM_RELATIONSHIPS__ as b ON b.object_id = a.id')
					->join('RIGHT JOIN __SYSTEM_TERMS__ as c ON c.term_id = b.term_id')
					->field('a.*,b.object_id,c.term_id')
					->where($condition)
					->where("c.term_id = $term_id")
					->select();
			}
		}
		//将人物对应图片查询放入数组
		foreach($screening_results as $key => $value){
			$imgInfo = $this->pub_img->where("person_id =".$value['id'])->find();
			$screening_results[$key]['img_url'] = $imgInfo['img_url'];
		}
		echo json_encode($screening_results,true);
	}
	/*高级搜索条件查询结果--资料检索*/
	public function data_search(){
		$term_id = I("term_id"); //总分类id
		$keyword = I("keyword"); //关键字
		$condition = I("condition"); //搜索类型
		if($term_id == 0){ //没有选择总分类时
			foreach($condition as $key => $value){
				switch ($value){
					case 'img':
						$where_img['img_name|img_text'] = array('like',"%$keyword%");
						$where_img['img_mark'] = 1;
						$imgArr = $this->pub_img
							->where($where_img)
							->select();
						$allArr['img'] = $imgArr;
						$allArr['img_keyword'] = $keyword;
						break;
					case 'story':
						$where_story['title'] = array('like',"%$keyword%");
						$storyArr = $this->pub_story
							->where($where_story)
							->select();
						for($i=0;$i<count($storyArr);$i++){
							$storyArr[$i]['content']=htmlspecialchars_decode($storyArr[$i]['content']);
						}
						$allArr['story'] = $storyArr;
						break;
					case 'video':
						$where_video['v_name'] = array('like',"%$keyword%");
						$videoArr = $this->pub_video
							->where($where_video)
							->select();
						$allArr['video'] = $videoArr;
						break;
					case 'course':
						$where_course['content'] = array('like',"%$keyword%");
						$courseArr = $this->pub_history
							->where($where_course)
							->select();
						for($i=0;$i<count($courseArr);$i++){
							$courseArr[$i]['content']=htmlspecialchars_decode($courseArr[$i]['content']);
						}
						$allArr['course'] = $courseArr;
						break;
					case 'rest':
						$where_rest['title'] = array('like',"%$keyword%");
						$restArr = $this->pub_information
							->where($where_rest)
							->select();
						for($i=0;$i<count($restArr);$i++){
							$info_imgs=$this->pub_img
								->where(array("img_mark"=>2,"infor_id"=>$restArr[$i]['id']))
								->select();
							$restArr[$i]['imgs']=$info_imgs;
							$restArr[$i]['content']=htmlspecialchars_decode($restArr[$i]['content']);
						}

						$allArr['rest'] = $restArr;
						break;
				}
			}
		} else{ //有总分类的时候
			/*判断是否为一级类*/
			$grade = $this->sys_terms->find($term_id); //该分类下的信息
			$grade_num = count(explode('-',$grade['path']))-1; //获取分类等级数
			if($grade_num == 1){
				//是一级类情况，查询该一级类下的子分类信息
				$subclassification_info = $this->sys_terms->where("parent = $term_id")->select();
				foreach($subclassification_info as $key => $value){
					$subclassification_info_belong[$key] = $this->sys_terms_relationships->field('object_id,term_id')->where("term_id = ".$value['term_id'])->select(); //查询出二级分类下的人物id object_id
				}
				$i = 0;
				foreach($subclassification_info_belong as $key => $value){
					foreach($value as $k => $v){
						$object_arr[$i++] = $v['object_id'];
					}
				}
				$object_ids = implode(',',$object_arr); //拿到该分类下的人物id，通过人物id来查询资料
				$map['person_id'] = array('in',$object_ids); //整合总分类搜索条件
			}else{ //是二级类情况,直接使用二级分类id查询
				$subclassification_info_belong = $this->sys_terms_relationships->field('object_id,term_id')->where("term_id = ".$term_id)->select(); //查询出二级分类下的人物id object_id
				foreach($subclassification_info_belong as $key => $value){
					$object_arr[$key] = $value['object_id'];
				}
				$object_ids = implode(',',$object_arr); //拿到该分类下的人物id，通过人物id来查询资料
				$map['person_id'] = array('in',$object_ids); //整合总分类搜索条件
			}
			foreach($condition as $key => $value){
				switch ($value){
					case 'img':
						$where_img['img_name|img_text'] = array('like',"%$keyword%");
						$where_img['img_mark'] = 1;
						$imgArr = $this->pub_img
							->where($where_img)
							->where($map)
							->select();
						$allArr['img'] = $imgArr;
						break;
					case 'story':
						$where_story['title'] = array('like',"%$keyword%");
						$storyArr = $this->pub_story
							->where($where_story)
							->where($map)
							->select();
						for($i=0;$i<count($storyArr);$i++){
							$storyArr[$i]['content']=htmlspecialchars_decode($storyArr[$i]['content']);
						}
						$allArr['story'] = $storyArr;
						break;
					case 'video':
						$where_video['v_name'] = array('like',"%$keyword%");
						$videoArr = $this->pub_video
							->where($where_video)
							->where($map)
							->select();
						$allArr['video'] = $videoArr;
						break;
					case 'course':
						$where_course['content'] = array('like',"%$keyword%");
						$courseArr = $this->pub_history
							->where($where_course)
							->where($map)
							->select();
						$allArr['course'] = $courseArr;
						break;
					case 'rest':
						$where_rest['title'] = array('like',"%$keyword%");
						$where_rest['person_id'] = array('in',$object_ids);
						$restArr = $this->pub_information
							->where($where_rest)
							->select();
						for($i=0;$i<count($restArr);$i++){
							$info_imgss=$this->pub_img
								->where(array("img_mark"=>2,"infor_id"=>$restArr[$i]['id']))
								->select();
							$restArr[$i]['imgs']=$info_imgss;
						}
						$allArr['rest'] = $restArr;
						break;
				}
			}
		}
		$allArr['img'] = $allArr['img'] ? $allArr['img']:array();
		$allArr['story']=$allArr['story'] ? $allArr['story']:array();
		$allArr['video']=$allArr['video'] ? $allArr['video'] :array();
		$allArr['course']=$allArr['course'] ? $allArr['course']:array();
		$allArr['rest']=$allArr['rest'] ? $allArr['rest']:array();
		echo json_encode($allArr,true);
//		$this->ajaxReturn($allArr);
	}
	// 获取文章分类树结构
	private function _getTermTree($term = array()) {
		$result = $this->terms_model->order(array("listorder" => "desc","term_id"=>"asc"))->select();
		$tree = new \Tree();
		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
		foreach ($result as $r) {
			$r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
			$r['visit'] = "<a href='#'>访问</a>";
			$r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
			$r['id'] = $r['term_id'];
			$r['parentid'] = $r['parent'];
			$r['selected'] = in_array($r['term_id'], $term) ? "selected" : "";
			$r['checked'] = in_array($r['term_id'], $term) ? "checked" : "";
			$array[] = $r;
		}
		$tree->init($array);
		$str = "<option value='\$id' \$selected >\$spacer\$name </option>";
		$taxonomys = $tree->get_tree(0, $str);
		$this->assign("taxonomys", $taxonomys);
	}

}
